package com.nowcoder.community.util;

import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

//敏感词过滤
@Component
public class SensitiveFilter {

    private static final Logger logger = LoggerFactory.getLogger(SensitiveFilter.class);
    //替换符
    private static final String REPLACEMENT = "***";

    //1.定义一个前缀树
    private class TrieNode{

        //关键词结束标识
        private boolean isKeywordEnd = false;

        //当前节点的子节点（可能有多个，所以用Map来封装,key是下级字符，value是下级节点）
        private Map<Character,TrieNode> subNodes = new HashMap<>();

        public boolean isKeywordEnd() {
            return isKeywordEnd;
        }

        public void setIsKeywordEnd(boolean isKeywordEnd) {
            this.isKeywordEnd = isKeywordEnd;
        }

        //添加子节点的方法
        public void addSubNode(Character c,TrieNode node){
            subNodes.put(c,node);
        }
        //获取子节点的方法
        public TrieNode getSubNode(Character c){
            return subNodes.get(c);
        }
    }

    //2.初始化前缀树

        //先初始化根节点
        TrieNode rootNode = new TrieNode();
        //该注解表明这是一个初始化方法
        @PostConstruct
        public void init(){
        try(
        //以字节流的形式得到敏感词文件的内容
        InputStream inputStream =
                this.getClass().getClassLoader().getResourceAsStream("sensitive-words.txt");
        //将字节流转化字符流再转化为缓冲流
        BufferedReader bufferedReader =
                new BufferedReader(new InputStreamReader(inputStream));
        )
        {
            String keyword;
            while ((keyword = bufferedReader.readLine()) != null){
                //添加到前缀树
                this.addKeyword(keyword);
            }
        } catch (Exception e) {
            logger.error("加载敏感词文件失败："+e.getMessage());
        }
    }

        //将一个敏感词添加到前缀树中
        private void addKeyword(String keyword){
        TrieNode tempNode = rootNode;
        for (int i = 0;i<keyword.length();++i){
            char c = keyword.charAt(i);
            TrieNode subNode = tempNode.getSubNode(c);
            if (subNode == null){
                //初始化子节点
                subNode = new TrieNode();
                tempNode.addSubNode(c,subNode);
            }
            //指针指向子节点,进入下一层循环
            tempNode = subNode;

            //设置结束的标识
            if (i == keyword.length()-1){
                tempNode.setIsKeywordEnd(true);
            }

        }
    }

    //3.过滤
    public String filter(String text){
        if (StringUtils.isBlank(text)){
            return null;
        }
        //指针1，指向前缀树
        TrieNode tempNode = rootNode;
        //指针2,指向字符串的开始下标
        int begin = 0;
        //指针3,，指向结束下标
        int position = 0;
        //记录最终结果
        StringBuilder stringBuilder = new StringBuilder();

        while (begin < text.length()){
            if (position < text.length()) {
                char c = text.charAt(position);
                //先跳过符号
                if (isSymbol(c)) {
                    //如果指针1在根节点，将此字符号计入结果，让指针2向下走一步
                    if (tempNode == rootNode) {
                        stringBuilder.append(c);
                        begin++;
                    }
                    position++;
                    continue;
                }
                //检查下级节点
                tempNode = tempNode.getSubNode(c);
                if (tempNode == null) {
                    //以begin开头的字符串 不是敏感词
                    stringBuilder.append(text.charAt(begin));
                    position = ++begin;
                    tempNode = rootNode;
                } else if (tempNode.isKeywordEnd()) {
                    //发现敏感词
                    stringBuilder.append(REPLACEMENT);
                    begin=++position;
                    tempNode = rootNode;
                } else {
                    //检查下一个字符
                    position++;
                }
            }else {
                //position越界仍然未发现敏感词
                stringBuilder.append(text.charAt(begin));
                position=++begin;
                tempNode=rootNode;
            }
        }
        return stringBuilder.toString();
    }
        //判断是否为符号
        private boolean isSymbol(Character c){
            // 0x2E80~0x9FFF 是东亚文字范围
            return !CharUtils.isAsciiAlphanumeric(c) && (c < 0x2E80 || c > 0x9FFF);
        }

}
